import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Button, Spin, message, Typography, Space, Tag, Divider } from 'antd';
import { ArrowLeftOutlined, CalendarOutlined, TagOutlined } from '@ant-design/icons';
import { notificationService } from '../services/api';
import { NotificationData } from '../types/api';

const { Title, Paragraph, Text } = Typography;

const NotificationDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [notification, setNotification] = useState<NotificationData | null>(null);

  useEffect(() => {
    if (id) {
      fetchNotificationDetail(parseInt(id));
    }
  }, [id]);

  const fetchNotificationDetail = async (notificationId: number) => {
    setLoading(true);
    try {
      const response = await notificationService.getNotificationDetail(notificationId);
      if (response.success && response.data) {
        setNotification(response.data);
      } else {
        message.error('获取通知详情失败');
        navigate('/notifications');
      }
    } catch (error) {
      console.error('获取通知详情异常:', error);
      message.error('获取通知详情失败');
      navigate('/notifications');
    } finally {
      setLoading(false);
    }
  };

  const getTypeColor = (type: string) => {
    const typeColors: { [key: string]: string } = {
      system: 'blue',
      task_reminder: 'orange',
      achievement: 'gold',
      friend_request: 'green',
      message: 'purple',
      schedule: 'cyan',
      default: 'default'
    };
    return typeColors[type] || typeColors.default;
  };

  const getTypeText = (type: string) => {
    const typeTexts: { [key: string]: string } = {
      system: '系统通知',
      task_reminder: '任务提醒',
      achievement: '成就解锁',
      friend_request: '好友申请',
      message: '新消息',
      schedule: '日程提醒',
      default: '其他'
    };
    return typeTexts[type] || typeTexts.default;
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '400px' 
      }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!notification) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Text type="secondary">通知不存在或已被删除</Text>
        <br />
        <Button 
          type="primary" 
          onClick={() => navigate('/notifications')}
          style={{ marginTop: '16px' }}
        >
          返回通知列表
        </Button>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px', maxWidth: '800px', margin: '0 auto' }}>
      <Space style={{ marginBottom: '24px' }}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => navigate('/notifications')}
        >
          返回
        </Button>
      </Space>

      <Card>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <div>
            <Title level={2} style={{ marginBottom: '8px' }}>
              {notification.title}
            </Title>
            <Space>
              <Tag 
                color={getTypeColor(notification.type)}
                icon={<TagOutlined />}
              >
                {getTypeText(notification.type)}
              </Tag>
              <Tag color={notification.is_read ? 'green' : 'red'}>
                {notification.is_read ? '已读' : '未读'}
              </Tag>
            </Space>
          </div>

          <Divider />

          <div>
            <Text type="secondary" style={{ fontSize: '14px' }}>
              <CalendarOutlined style={{ marginRight: '4px' }} />
              创建时间：{formatDate(notification.created_at)}
            </Text>
          </div>

          <div>
            <Title level={4}>通知内容</Title>
            <Paragraph 
              style={{ 
                fontSize: '16px', 
                lineHeight: '1.6',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-word'
              }}
            >
              {notification.content}
            </Paragraph>
          </div>

          {notification.action_url && (
            <div>
              <Button 
                type="primary" 
                href={notification.action_url}
                target="_blank"
                rel="noopener noreferrer"
              >
                查看详情
              </Button>
            </div>
          )}

          {notification.related_id && notification.related_type && (
            <div>
              <Text type="secondary">
                关联对象：{notification.related_type} #{notification.related_id}
              </Text>
            </div>
          )}
        </Space>
      </Card>
    </div>
  );
};

export default NotificationDetail;
